<%@page import="javax.imageio.ImageIO"%>
<%@page import="java.awt.Font"%>
<%@page import="java.awt.Color"%>
<%@page import="java.util.Random"%>
<%@page import="java.awt.Graphics2D"%>
<%@page import="java.awt.image.BufferedImage"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		int width = 60;
		int height = 20;
		//创建具有可访问图像的数据缓冲区的Image
		BufferedImage buffImg = 
		new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
	
		Graphics2D gh = buffImg.createGraphics();
	
		//创建一个随机数生成器
		Random random = new Random();
		gh.setColor(Color.WHITE);
		gh.fillRect(0, 0, width, height);
		
		//创建字体，字体大小根据图片高度来定
		Font font = new Font("Times New Roman",Font.PLAIN, 18);
		//设置字体
		gh.setFont(font);
		
		//画边框
		gh.setColor(Color.BLACK);
		gh.drawRect(0, 0, width-1, height-1);
		
		//随机生成160条干扰线
		gh.setColor(Color.LIGHT_GRAY);
		for(int i = 0; i< 160;i++){
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int x1 = random.nextInt(12);
			int y1 = random.nextInt(12);
			
			gh.drawLine(x, y, x + x1, y + y1);
		}
		//randomcode用于保存随机产生的验证码
		StringBuffer randomCode = new StringBuffer();
		int red = 0,green = 0,blue = 0;
		
		String verification = "";
		
		
		//随机生成4位数字的验证码
		for(int i = 0; i < 4; i++){
			//得到随机产生的验证码数字0
			String strRandom = String.valueOf(random.nextInt(10));
			verification += strRandom;
			//产生随机的颜色来构造颜色的值
			red = random.nextInt(110);
			green = random.nextInt(50);
			blue = random.nextInt(50);
			//用随机生成的颜色将验证码绘制到图像中
			gh.setColor(new Color(red,green,blue));
			gh.drawString(strRandom, 13*i+6, 16);
			randomCode.append(strRandom);
		}
		/* System.out.print(verification); */
		//将四位数字的验证码保存到session中
		session.setAttribute("randomCode", randomCode.toString());
		
		//禁止图像缓存
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		
		response.setContentType("image/jpeg");
		//将图像输出到servlet输出流中
		ServletOutputStream sos = response.getOutputStream();
		ImageIO.write(buffImg, "jpeg", sos);
		//关闭流
		sos.close();
		out.clear();
		out = pageContext.pushBody();
	%>
</body>
</html>